/**********************************************
*  Classes:   GLRenderer
*  Desc:      Renders a scene graph using OpenGL.
*			  Singleton class
*  Author:    Vaios Kalpias-Ilias (C) 2008-2009
***********************************************/

#include "GLRenderer.h"
#include "GeometryNode.h"
#include "Swap.h"
#include "Quaternion.h"
#include "Helper.h"
#include "GameApp.h"
#include "MaterialProperty.h"
#include "Camera.h"
#include "SkyBox.h"

using namespace boost;

//-----------------------------------------------
/**
* Ctor
*/
GLRenderer::GLRenderer()
: m_hRC(0),
  m_uiSkyBoxDL(0)
{
}
//-----------------------------------------------
/**
* Dtor
*/
GLRenderer::~GLRenderer()
{
	if (m_bWindowCreated)
	{
		DestroyRenderWindow();
	}

}
//-----------------------------------------------
/**
* Deletes vbo's etc.
*/
void GLRenderer::UnloadGeometry()
{
	if (m_bInitialized)
	{
		RenderList::iterator it;
		for (it = m_lRenderStructs.begin();
			it != m_lRenderStructs.end();
			++it)
		{
			unsigned int nBuffers[3] = 
			{ (*it)->verticesName, 
			(*it)->normalsName,  
			(*it)->texCoordsName};
			glDeleteBuffersARB( 3, nBuffers );

			delete (*it);
		}

		m_lRenderStructs.clear();
	}

	if (m_uiSkyBoxDL)
	{
		glDeleteLists(m_uiSkyBoxDL, 1);
		m_uiSkyBoxDL = 0;
	}

	ClearSorted();
}
//-----------------------------------------------
/**
* Initializes renderer
*/
bool GLRenderer::Init(HINSTANCE &hInstance, 
					  bool fullscreen,
					  int width,
					  int height,
					  const char* title)
{
	
	if (!CreateRendererWindow(hInstance, fullscreen, width, height, title))
		return false;

	if (!IsVBOExtensionSupported())
		return false;

	// VBO Function Pointers
	glDeleteBuffersARB = 
			(PFNGLDELETEBUFFERSARBPROC) wglGetProcAddress("glDeleteBuffersARB");

	glBindBufferARB = 
			((PFNGLBINDBUFFERARBPROC) wglGetProcAddress("glBindBufferARB"));

	glGenBuffersARB = 
			((PFNGLGENBUFFERSARBPROC) wglGetProcAddress("glGenBuffersARB"));

	glBufferDataARB = 
			((PFNGLBUFFERDATAARBPROC) wglGetProcAddress("glBufferDataARB"));

	m_spCamera = CameraPtr(new Camera);
	

	return m_bInitialized = true;
}
//-----------------------------------------------
/**
* Creates an OpenGL window
*/
bool GLRenderer::CreateRendererWindow(HINSTANCE &hInstance, 
									  bool fullscreen,
									  int width,
									  int height,
									  const char* title)
{
	m_iWidth = width;
	m_iHeight = height;
	m_fAspectRatio = (float)width / (float)height;

	GLuint		PixelFormat;			// Holds The Results After Searching For A Match
	WNDCLASS	wc;						// Windows Class Structure
	DWORD		dwExStyle;				// Window Extended Style
	DWORD		dwStyle;				// Window Style
	RECT		WindowRect;				// Grabs Rectangle Upper Left / Lower Right Values
	WindowRect.left=(long)0;			// Set Left Value To 0
	WindowRect.right=(long)width;		// Set Right Value To Requested Width
	WindowRect.top=(long)0;				// Set Top Value To 0
	WindowRect.bottom=(long)height;		// Set Bottom Value To Requested Height

	m_bFullscreen = fullscreen;			// Set The Global Fullscreen Flag

	m_hInstance			= hInstance;				// Grab An Instance For Our Window
	wc.style			= CS_HREDRAW | CS_VREDRAW | CS_OWNDC;	// Redraw On Size, And Own DC For Window.
	wc.lpfnWndProc		= (WNDPROC) GameApp::MsgHandler;		// WndProc Handles Messages
	wc.cbClsExtra		= 0;									// No Extra Window Data
	wc.cbWndExtra		= 0;									// No Extra Window Data
	wc.hInstance		= m_hInstance;							// Set The Instance
	wc.hIcon			= LoadIcon(0, IDI_WINLOGO);				// Load The Default Icon
	wc.hCursor			= LoadCursor(0, IDC_ARROW);				// Load The Arrow Pointer
	wc.hbrBackground	= 0;									// No Background Required For GL
	wc.lpszMenuName		= 0;									// We Don't Want A Menu
	wc.lpszClassName	= m_cfClassName;						// Set The Class Name

	if (!RegisterClass(&wc))									// Attempt To Register The Window Class
	{
		MessageBox(0,"Failed To Register The Window Class.","ERROR",MB_OK|MB_ICONEXCLAMATION);
		return false;											// Return FALSE
	}

	if (m_bFullscreen)											// Attempt Fullscreen Mode?
	{
		DEVMODE dmScreenSettings;								// Device Mode
		memset(&dmScreenSettings,0,sizeof(dmScreenSettings));	// Makes Sure Memory's Cleared
		dmScreenSettings.dmSize=sizeof(dmScreenSettings);		// Size Of The Devmode Structure
		dmScreenSettings.dmPelsWidth	= width;				// Selected Screen Width
		dmScreenSettings.dmPelsHeight	= height;				// Selected Screen Height
		dmScreenSettings.dmBitsPerPel	= 32;					// Selected Bits Per Pixel
		dmScreenSettings.dmFields=DM_BITSPERPEL|DM_PELSWIDTH|DM_PELSHEIGHT;

		// Try To Set Selected Mode And Get Results.  NOTE: CDS_FULLSCREEN Gets Rid Of Start Bar.
		if (ChangeDisplaySettings(&dmScreenSettings,CDS_FULLSCREEN)!=DISP_CHANGE_SUCCESSFUL)
		{
			// If The Mode Fails, Offer Two Options.  Quit Or Use Windowed Mode.
			if (MessageBox(0,"The Requested Fullscreen Mode Is Not Supported By\nYour Video Card. Use Windowed Mode Instead?",
				"Warning",MB_YESNO|MB_ICONEXCLAMATION)==IDYES)
			{
				m_bFullscreen = false;		// Windowed Mode Selected.  Fullscreen = FALSE
			}
			else
			{
				// Pop Up A Message Box Letting User Know The Program Is Closing.
				MessageBox(0,"Program Will Now Close.","ERROR",MB_OK|MB_ICONSTOP);
				return FALSE;									// Return FALSE
			}
		}
	}

	if (m_bFullscreen)												// Are We Still In Fullscreen Mode?
	{
		dwExStyle=WS_EX_APPWINDOW;								// Window Extended Style
		dwStyle=WS_POPUP;										// Windows Style		
	}
	else
	{
		dwExStyle=WS_EX_APPWINDOW | WS_EX_WINDOWEDGE;			// Window Extended Style
		dwStyle=WS_OVERLAPPEDWINDOW;							// Windows Style
	}

	AdjustWindowRectEx(&WindowRect, dwStyle, FALSE, dwExStyle);		// Adjust Window To True Requested Size

	// Create The Window
	if (!(m_hWnd=CreateWindowEx( dwExStyle,							
		m_cfClassName,					// Class Name
		title,								// Window Title
		dwStyle |							// Defined Window Style
		WS_CLIPSIBLINGS |					// Required Window Style
		WS_CLIPCHILDREN,					// Required Window Style
		0, 0,								// Window Position
		WindowRect.right-WindowRect.left,	// Calculate Window Width
		WindowRect.bottom-WindowRect.top,	// Calculate Window Height
		0,								// No Parent Window
		0,								// No Menu
		m_hInstance,					// Instance
		0)))							// Dont Pass Anything To WM_CREATE
	{
		DestroyRenderWindow();								// Reset The Display
		MessageBox(0,"Window Creation Error.","ERROR",MB_OK|MB_ICONEXCLAMATION);
		return false;								// Return FALSE
	}

	static	PIXELFORMATDESCRIPTOR pfd=				// pfd Tells Windows How We Want Things To Be
	{
		sizeof(PIXELFORMATDESCRIPTOR),				// Size Of This Pixel Format Descriptor
		1,											// Version Number
		PFD_DRAW_TO_WINDOW |						// Format Must Support Window
		PFD_SUPPORT_OPENGL |						// Format Must Support OpenGL
		PFD_DOUBLEBUFFER,							// Must Support Double Buffering
		PFD_TYPE_RGBA,								// Request An RGBA Format
		32,										// Select Our Color Depth
		0, 0, 0, 0, 0, 0,							// Color Bits Ignored
		0,											// No Alpha Buffer
		0,											// Shift Bit Ignored
		0,											// No Accumulation Buffer
		0, 0, 0, 0,									// Accumulation Bits Ignored
		16,											// 16Bit Z-Buffer (Depth Buffer)  
		0,											// No Stencil Buffer
		0,											// No Auxiliary Buffer
		PFD_MAIN_PLANE,								// Main Drawing Layer
		0,											// Reserved
		0, 0, 0										// Layer Masks Ignored
	};

	if (!(m_hDC=GetDC(m_hWnd)))							// Did We Get A Device Context?
	{
		DestroyRenderWindow();								// Reset The Display
		MessageBox(0,"Can't Create A GL Device Context.","ERROR",MB_OK|MB_ICONEXCLAMATION);
		return false;								// Return FALSE
	}

	if (!(PixelFormat=ChoosePixelFormat(m_hDC,&pfd)))	// Did Windows Find A Matching Pixel Format?
	{
		DestroyRenderWindow();								// Reset The Display
		MessageBox(0,"Can't Find A Suitable PixelFormat.","ERROR",MB_OK|MB_ICONEXCLAMATION);
		return false;								// Return FALSE
	}

	if(!SetPixelFormat(m_hDC,PixelFormat,&pfd))		// Are We Able To Set The Pixel Format?
	{
		DestroyRenderWindow();								// Reset The Display
		MessageBox(0,"Can't Set The PixelFormat.","ERROR",MB_OK|MB_ICONEXCLAMATION);
		return false;								// Return FALSE
	}

	if (!(m_hRC=wglCreateContext(m_hDC)))				// Are We Able To Get A Rendering Context?
	{
		DestroyRenderWindow();								// Reset The Display
		MessageBox(0,"Can't Create A GL Rendering Context.","ERROR",MB_OK|MB_ICONEXCLAMATION);
		return false;								// Return FALSE
	}

	if(!wglMakeCurrent(m_hDC,m_hRC))					// Try To Activate The Rendering Context
	{
		DestroyRenderWindow();								// Reset The Display
		MessageBox(0,"Can't Activate The GL Rendering Context.","ERROR",MB_OK|MB_ICONEXCLAMATION);
		return false;								// Return FALSE
	}

	// show window
	ShowWindow(m_hWnd,SW_SHOW);			// Show The Window
	SetForegroundWindow(m_hWnd);		// Slightly Higher Priority
	SetFocus(m_hWnd);

	ResizeWindow(width, height);				// Set Up Our Perspective GL Screen

	return m_bWindowCreated = true;									// Success
}
//-----------------------------------------------
/**
* Destroys current window
*/
void GLRenderer::DestroyRenderWindow()
{
	if (m_bFullscreen)										// Are We In Fullscreen Mode?
	{
		ChangeDisplaySettings(0,0);					// If So Switch Back To The Desktop
		ShowCursor(true);								// Show Mouse Pointer
	}

	if (m_hRC)											// Do We Have A Rendering Context?
	{
		if (!wglMakeCurrent(0,0))					// Are We Able To Release The DC And RC Contexts?
		{
			MessageBox(0,"Release Of DC And RC Failed.","SHUTDOWN ERROR",MB_OK | MB_ICONINFORMATION);
		}

		if (!wglDeleteContext(m_hRC))						// Are We Able To Delete The RC?
		{
			MessageBox(0,"Release Rendering Context Failed.","SHUTDOWN ERROR",MB_OK | MB_ICONINFORMATION);
		}
		m_hRC=0;										// Set RC To 0
	}

	if (m_hDC && !ReleaseDC(m_hWnd,m_hDC))					// Are We Able To Release The DC
	{
		MessageBox(0,"Release Device Context Failed.","SHUTDOWN ERROR",MB_OK | MB_ICONINFORMATION);
		m_hDC=0;										// Set DC To 0
	}

	if (m_hWnd && !DestroyWindow(m_hWnd))					// Are We Able To Destroy The Window?
	{
		MessageBox(0,"Could Not Release hWnd.","SHUTDOWN ERROR",MB_OK | MB_ICONINFORMATION);
		m_hWnd=0;										// Set hWnd To 0
	}

	if (!UnregisterClass(m_cfClassName,m_hInstance))			// Are We Able To Unregister Class
	{
		MessageBox(0,"Could Not Unregister Class.","SHUTDOWN ERROR",MB_OK | MB_ICONINFORMATION);
		m_hInstance=0;									// Set hInstance To 0
	}

	m_bWindowCreated = false;
}
//-----------------------------------------------
/**
* Resizes OpenGL window
*/
void GLRenderer::ResizeWindow(int width, int height)
{
	if (height==0)										// Prevent A Divide By Zero By
	{
		height=1;										// Making Height Equal One
	}

	glViewport(0,0,width,height);						// Reset The Current Viewport

	m_iWidth = width;
	m_iHeight = height;
	m_fAspectRatio = (GLfloat)width/(GLfloat)height;

	glMatrixMode(GL_PROJECTION);						// Select The Projection Matrix
	glLoadIdentity();									// Reset The Projection Matrix

	if (m_spCamera)
	{
		if (m_spCamera->UpdateProjectionFlag())
		{
			gluPerspective(m_spCamera->GetFOV(),m_fAspectRatio,
				m_spCamera->GetNearDist(),m_spCamera->GetFarDist());
			m_spCamera->SetUpdateProjectionFlag(false);
		}
		else
		{
			gluPerspective(45.0f,m_fAspectRatio,1.0f,300.0f);
			m_spCamera->SetUpdateFrustrum(true);
		}
	}
	else
	{
		gluPerspective(45.0f,m_fAspectRatio,1.0f,300.0f);
	}

	glMatrixMode(GL_MODELVIEW);							// Select The Modelview Matrix
	glLoadIdentity();
}
//-----------------------------------------------
/**
* Renders scene
*/
void GLRenderer::RenderScene(SceneNode *scene)
{
	if (!scene) return;

	// update camera
	if (!m_spCamera->GetParent())
		m_spCamera->Update();

	if (m_spCamera->UpdateProjectionFlag())
	{
		ResizeWindow(m_iWidth, m_iHeight);
	}
	// Clear The Screen And The Depth Buffer
	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);	
	
	// Reset The View
	glLoadIdentity();			
	
	// setup OpenGL camera
	const mth::Vector3& pos    = m_spCamera->GetGlobalTranslation();
	const mth::Vector3& target = m_spCamera->GetTargetPos();
	const mth::Vector3& up = m_spCamera->GetGlobalUp();
	gluLookAt(pos.x, pos.y, pos.z,
		      target.x, target.y, target.z,
			  up.x, up.y, up.z);
			  
	// sort states
	SortScene(scene);

	// set the background color
	glClearColor(m_vBackgroundColor.x, 
		m_vBackgroundColor.y, 
		m_vBackgroundColor.z,
		1.0);
	
	// enable OpenGL stuff
	glShadeModel(GL_SMOOTH);
	glEnable(GL_NORMALIZE);
	glEnable(GL_DEPTH_TEST);
	glDepthFunc(GL_LEQUAL);
	glEnable(GL_CULL_FACE);
	//glEnable(GL_POLYGON_SMOOTH);
	/*
	glEnable(GL_FOG);
	float fogColor[3] = {0.0f, 0.0f, 0.5f};
	glFogfv(GL_FOG_COLOR, fogColor);
	glFogi(GL_FOG_MODE, GL_LINEAR);
	glFogf(GL_FOG_START, 50.0f);
	glFogf(GL_FOG_END, 500.0f);
	*/
	//glEnable(GL_BLEND);
	//glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

	

	// render sorted geometry
	RenderSorted();
	
	// draw skybox
	if (m_spSkyBox)
	{
		if (m_spSkyBox->GetMoveWithCamera())
		{
			const mth::Vector3& pos = m_spCamera->GetGlobalTranslation();
			glPushMatrix();
			glTranslatef(pos.x, pos.y, pos.z);
			glCallList(m_uiSkyBoxDL);
			glPopMatrix();
		}
		else
		{
			glCallList(m_uiSkyBoxDL);
		}
	}

	// disable all OpenGL states
	//glDisable(GL_BLEND);
	//glDisable(GL_FOG);
	//glDisable(GL_POLYGON_SMOOTH);
	glDisable(GL_CULL_FACE);
	glDisable(GL_DEPTH_TEST);
	glDisable(GL_NORMALIZE);
	
	// clear sorted lists
	ClearSorted();
}
//-----------------------------------------------
/**
* Sorts states in scene
*/
void GLRenderer::SortScene(SceneNode *scene)
{
	if (scene->DerivesFromTransform())
	{
		if (!IsVisible(static_cast<TransformNode*>(scene)))
		{
			return;
		}

	}
	else
		return;

	// if this is a geometry node
	if (scene->DerivesFromGeometry())
	{
		// create a SortStruct and add it 
		GeometryNode* geom = static_cast<GeometryNode*>(scene);

		TexturePropertyPtr tex  = static_pointer_cast<TextureProperty>
			(geom->GetProperty(NodeProperty::PROPERTY_TEXTURE));


		MaterialPropertyPtr mat  = static_pointer_cast<MaterialProperty>
			(geom->GetProperty(NodeProperty::PROPERTY_MATERIAL));

		unsigned int vboId = geom->GetVerticesName();

		TextureProperty* texP = 0;
		if (tex)
		{
			texP = tex.get();
		}

		MaterialProperty* matP = 0;
		if (mat)
		{
			matP = mat.get();
		}
		TexturesMap::iterator texIt = m_SortedGeometry.find(texP);
		if ( texIt != m_SortedGeometry.end())
		{
			MaterialMap::iterator matIt = texIt->second->find(matP);
			if (matIt != texIt->second->end())
			{
				GeometryMap::iterator geomIt = matIt->second->find(vboId);
				if (geomIt != matIt->second->end())
				{
					geomIt->second->push_back(geom);
					//matIt->second->push_back(geom);
				}
				else
				{
					GeometryList* l = new GeometryList;
					l->push_back(geom);
					matIt->second->insert(make_pair(vboId, l));
				}
				
			}
			else
			{
				GeometryList* l = new GeometryList;
				l->push_back(geom);
				GeometryMap* geomMap = new GeometryMap;
				geomMap->insert(make_pair(vboId, l));
				texIt->second->insert(make_pair(matP, geomMap));
			}
		}
		else
		{
			GeometryList* l = new GeometryList;
			l->push_back(geom);
			GeometryMap* geomMap = new GeometryMap;
			geomMap->insert(make_pair(vboId, l));
			MaterialMap* m = new MaterialMap;
			m->insert(make_pair(matP, geomMap));
			m_SortedGeometry.insert(make_pair(texP, m));
		}
	}

	// do the same for the children
	const SceneNode::NodeList children = scene->GetChildren();
	SceneNode::NodeList::const_iterator it;
	for (it = children.begin();
		it != children.end();
		++it)
	{
		SortScene((*it).get());
	}
}
//----------------------------------------------
/**
* Renders sorted geometry
*/
void GLRenderer::RenderSorted()
{

	bool textureBinded = false;

	TexturesMap::iterator texIt = m_SortedGeometry.begin();
	for (; texIt != m_SortedGeometry.end(); ++texIt)
	{
		//textureBinded = false;
		TextureProperty* texture = texIt->first;
		if (texture)
		{
			glEnable(GL_TEXTURE_2D);
			EnableTextures(texture);	
			
		}

		MaterialMap::iterator matIt = texIt->second->begin();

		for (; matIt != texIt->second->end(); ++matIt)
		{
			//bool materialBinded = false;
			MaterialProperty* material = matIt->first;
			if (material)
			{
				EnableMaterial(material);	
			}

			GeometryMap::iterator geomMapIt = matIt->second->begin();
			for (; geomMapIt != matIt->second->end(); ++geomMapIt)
			{
				bool vboBinded = false;
				GeometryNode* node = 0;
				GeometryList::iterator geomIt = geomMapIt->second->begin();
				for (; geomIt != geomMapIt->second->end(); ++geomIt)
				{
					node = *geomIt;
					
					EnableLights(node);

					if (!vboBinded)
					{
						vboBinded = true;
						EnableVertices(node);
						EnableNormals(node);
						EnableTexCoords(node);						
					}
					
					// set transform matrix
					glPushMatrix();

					// translate
					glTranslatef(node->GetGlobalTranslation().x, 
						node->GetGlobalTranslation().y,
						node->GetGlobalTranslation().z);

					// rotate
					float angle;
					mth::Vector3 axis;
					node->GetGlobalRotationQuat().GetAxisAngle(axis,angle);
					glRotatef(angle*mth::TO_DEG, axis.x, axis.y, axis.z); 

					// scale
					glScalef(node->GetScale().x, node->GetScale().y, node->GetScale().z);



					// Draw All Of The Triangles At Once
					glDrawArrays( GL_TRIANGLES, 0, node->GetVerticesCount() );	

					// restore matrix
					glPopMatrix();
					
					
					DisableLights();
				}

				if (vboBinded && node)
				{
					DisableTexCoords(node);
					DisableNormals(node);
					DisableVertices(node);
				}
				
			}
			
		}

		if (texture)
		{
			glDisable(GL_TEXTURE_2D);
										
		}
	}

}
//----------------------------------------------
/**
* Clears sorted geometry map
*/
void GLRenderer::ClearSorted()
{
	TexturesMap::iterator it = m_SortedGeometry.begin();
	for (; it != m_SortedGeometry.end(); ++it)
	{
		MaterialMap::iterator mIt = it->second->begin();
		for(; mIt != it->second->end(); ++mIt)
		{
			GeometryMap::iterator gIt = mIt->second->begin();
			for (; gIt != mIt->second->end(); ++gIt)
			{
				gIt->second->clear();
				delete gIt->second;
			}
			mIt->second->clear();
			delete mIt->second;
		}

		it->second->clear();
		delete it->second;
	}

	m_SortedGeometry.clear();

}
//-----------------------------------------------
/**
* Sets the environment state for a texture
*/
void GLRenderer::SetTextureEnvState(unsigned int texId, TextureProperty::EnvironmentState state)
{
	if (texId)
	{
		glBindTexture(GL_TEXTURE_2D, texId);
		switch (state)
		{
		case TextureProperty::STATE_MODULATE:
			glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
			break;

		case TextureProperty::STATE_BLEND:
			glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_BLEND);
			break;

		case TextureProperty::STATE_REPLACE:
			glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
			break;
		default:
			return;
		}
	}
	
}
//-----------------------------------------------
/**
* Enables vertices
*/
void GLRenderer::EnableVertices(GeometryNode* node)
{
	if (node->GetVerticesName())
	{
		// Enable Pointers
		// Enable Vertex Arrays
		glEnableClientState( GL_VERTEX_ARRAY );		
		glBindBufferARB( GL_ARRAY_BUFFER_ARB, node->GetVerticesName());
		// Set The Vertex Pointer To The Vertex Buffer
		glVertexPointer( 3, GL_FLOAT, 0, (char *) 0 );
	}
}
//-----------------------------------------------
/**
* Disables vertices
*/
void GLRenderer::DisableVertices(GeometryNode* node)
{
	if (node->GetVerticesName())
	{
		glDisableClientState( GL_VERTEX_ARRAY );
	}
}
//-----------------------------------------------
/**
* Enables normals
*/
void GLRenderer::EnableNormals(GeometryNode* node)
{
	if (node->GetNormalsName())
	{
		// Enable Normal Arrays
		glEnableClientState( GL_NORMAL_ARRAY );
		glBindBufferARB( GL_ARRAY_BUFFER_ARB, node->GetNormalsName());
		// Set The Vertex Pointer To The Normal Buffer
		glNormalPointer( GL_FLOAT, 0, (char *) 0 );
	}
}
//-----------------------------------------------
/**
* Disables normals
*/
void GLRenderer::DisableNormals(GeometryNode* node)
{
	if (node->GetNormalsName())
	{
		glDisableClientState( GL_NORMAL_ARRAY );
	}
}
//-----------------------------------------------
/**
* Enables tex coords
*/
void GLRenderer::EnableTexCoords(GeometryNode* node)
{
	if (node->GetTexCoordsName())
	{
		// Enable Texture Coord Arrays
		glEnableClientState( GL_TEXTURE_COORD_ARRAY );	
		glBindBufferARB( GL_ARRAY_BUFFER_ARB, node->GetTexCoordsName());
		// Set The TexCoord Pointer To The TexCoord Buffer
		glTexCoordPointer( 2, GL_FLOAT, 0, (char *) 0 );	
	}
}
//-----------------------------------------------
/**
* Disables tex coords
*/
void GLRenderer::DisableTexCoords(GeometryNode* node)
{
	if (node->GetTexCoordsName())
	{
		glDisableClientState( GL_TEXTURE_COORD_ARRAY );	
	}
}
//-----------------------------------------------
/**
* Enables textures
*/
void GLRenderer::EnableTextures(TextureProperty* tex)
{
	glBindTexture(GL_TEXTURE_2D, tex->GetId());
}
//-----------------------------------------------
/**
* Enables a material
*/
void GLRenderer::EnableMaterial(MaterialProperty* mat)
{	
	const mth::Vector3& ambient = mat->GetAmbient();
	const mth::Vector3& diffuse = mat->GetDiffuse();
	const mth::Vector3& specular = mat->GetSpecular();
	const mth::Vector3& emissive = mat->GetEmissive();
	float alpha = mat->GetAlpha();
	float ambientv[] = {ambient.x, ambient.y, ambient.z, 1.0f};
	float diffusev[] = {diffuse.x, diffuse.y, diffuse.z, alpha};
	float specularv[] = {specular.x, specular.y, specular.z, 1.0f};
	float emissivev[] = {emissive.x, emissive.y, emissive.z, 1.0f};
	float shininess = mat->GetShininess();
	glMaterialfv(GL_FRONT, GL_AMBIENT, ambientv);
	glMaterialfv(GL_FRONT, GL_DIFFUSE, diffusev);
	glMaterialfv(GL_FRONT, GL_SPECULAR, specularv);
	glMaterialfv(GL_FRONT, GL_EMISSION, emissivev);
	glMaterialf(GL_FRONT, GL_SHININESS, shininess);
}

//-----------------------------------------------
/**
* Enables lights for a node
*/
void GLRenderer::EnableLights(GeometryNode* node)
{
	const TransformNode::LightList& lights =
		node->GetLightList();
	
	glEnable(GL_LIGHTING);
	TransformNode::LightList::const_iterator it;
	unsigned int num = 0;
	for (it = lights.begin();
		it != lights.end();
		++it)
	{
		if ((*it)->IsOn())
			EnableLight((*it), num);
		if (++num > 8) return;
	}
}
//-----------------------------------------------
/**
* Enables one of 8 lights
*/
void GLRenderer::EnableLight(LightPtr light,
							 unsigned int num)
{
	const mth::Vector3& ambient = light->GetAmbient();
	const mth::Vector3& diffuse = light->GetDiffuse();
	const mth::Vector3& specular = light->GetSpecular();
	const mth::Vector3& pos = light->GetPosition();
	float ambientv[] = {ambient.x, ambient.y, ambient.z, 1.0f};
	float diffusev[] = {diffuse.x, diffuse.y, diffuse.z, 1.0f};
	float specularv[] = {specular.x, specular.y, specular.z, 1.0f};
	float posv[] = {pos.x, pos.y, pos.z, 1.0f};
	switch (num)
	{
	case 0:
		glLightfv(GL_LIGHT0, GL_AMBIENT, ambientv);
		glLightfv(GL_LIGHT0, GL_DIFFUSE, diffusev);
		glLightfv(GL_LIGHT0, GL_SPECULAR, specularv);
		glLightfv(GL_LIGHT0, GL_POSITION, posv);
		glEnable(GL_LIGHT0);
		break;
	case 1:
		glLightfv(GL_LIGHT1, GL_AMBIENT, ambientv);
		glLightfv(GL_LIGHT1, GL_DIFFUSE, diffusev);
		glLightfv(GL_LIGHT1, GL_SPECULAR, specularv);
		glLightfv(GL_LIGHT1, GL_POSITION, posv);
		glEnable(GL_LIGHT1);
		break;
	case 2:
		glLightfv(GL_LIGHT2, GL_AMBIENT, ambientv);
		glLightfv(GL_LIGHT2, GL_DIFFUSE, diffusev);
		glLightfv(GL_LIGHT2, GL_SPECULAR, specularv);
		glLightfv(GL_LIGHT2, GL_POSITION, posv);
		glEnable(GL_LIGHT2);
		break;
	case 3:
		glLightfv(GL_LIGHT3, GL_AMBIENT, ambientv);
		glLightfv(GL_LIGHT3, GL_DIFFUSE, diffusev);
		glLightfv(GL_LIGHT3, GL_SPECULAR, specularv);
		glLightfv(GL_LIGHT3, GL_POSITION, posv);
		glEnable(GL_LIGHT3);
		break;
	case 4:
		glLightfv(GL_LIGHT4, GL_AMBIENT, ambientv);
		glLightfv(GL_LIGHT4, GL_DIFFUSE, diffusev);
		glLightfv(GL_LIGHT4, GL_SPECULAR, specularv);
		glLightfv(GL_LIGHT4, GL_POSITION, posv);
		glEnable(GL_LIGHT4);
		break;
	case 5:
		glLightfv(GL_LIGHT5, GL_AMBIENT, ambientv);
		glLightfv(GL_LIGHT5, GL_DIFFUSE, diffusev);
		glLightfv(GL_LIGHT5, GL_SPECULAR, specularv);
		glLightfv(GL_LIGHT5, GL_POSITION, posv);
		glEnable(GL_LIGHT5);
		break;
	case 6:
		glLightfv(GL_LIGHT6, GL_AMBIENT, ambientv);
		glLightfv(GL_LIGHT6, GL_DIFFUSE, diffusev);
		glLightfv(GL_LIGHT6, GL_SPECULAR, specularv);
		glLightfv(GL_LIGHT6, GL_POSITION, posv);
		glEnable(GL_LIGHT6);
		break;
	case 7:
		glLightfv(GL_LIGHT7, GL_AMBIENT, ambientv);
		glLightfv(GL_LIGHT7, GL_DIFFUSE, diffusev);
		glLightfv(GL_LIGHT7, GL_SPECULAR, specularv);
		glLightfv(GL_LIGHT7, GL_POSITION, posv);
		glEnable(GL_LIGHT7);
		break;
	default:
		return;
	}
}
//-----------------------------------------------
/**
* Disables lighting
*/
void GLRenderer::DisableLights()
{
	glDisable(GL_LIGHT7);
	glDisable(GL_LIGHT6);
	glDisable(GL_LIGHT5);
	glDisable(GL_LIGHT4);
	glDisable(GL_LIGHT3);
	glDisable(GL_LIGHT2);
	glDisable(GL_LIGHT1);
	glDisable(GL_LIGHT0);

	glDisable(GL_LIGHTING);
}
//----------------------------------------------
/**
* Creates vertices, normals etc for a node
*/
bool GLRenderer::BindNodeToMesh(GeometryNode* node,
				    mth::Vector3* vertices,
					mth::Vector3* normals,
					mth::Vector2* texCoords,
					int numOfVertices)
{
	
	RenderStruct* renderStruct = new RenderStruct();
	// Get A Valid Name
	glGenBuffersARB( 1, &renderStruct->verticesName );		
	// Bind The Buffer
	glBindBufferARB( GL_ARRAY_BUFFER_ARB, renderStruct->verticesName );			
	// Load The Data
	glBufferDataARB( GL_ARRAY_BUFFER_ARB, 
		numOfVertices*sizeof(mth::Vector3), vertices, GL_STATIC_DRAW_ARB );

	if (normals)
	{
		// Get A Valid Name
		glGenBuffersARB( 1, &renderStruct->normalsName );		
		// Bind The Buffer
		glBindBufferARB( GL_ARRAY_BUFFER_ARB, renderStruct->normalsName );			
		// Load The Data
		glBufferDataARB( GL_ARRAY_BUFFER_ARB, 
			numOfVertices*sizeof(mth::Vector3), normals, GL_STATIC_DRAW_ARB );

	}

	if (texCoords)
	{
		// Generate And Bind The Texture Coordinate Buffer
		// Get A Valid Name
		glGenBuffersARB( 1, &renderStruct->texCoordsName );							
		// Bind The Buffer
		glBindBufferARB( GL_ARRAY_BUFFER_ARB, renderStruct->texCoordsName );		
		// Load The Data
		glBufferDataARB( GL_ARRAY_BUFFER_ARB, 
			numOfVertices*sizeof(mth::Vector2), texCoords, GL_STATIC_DRAW_ARB );

	}

	renderStruct->numOfVertices = numOfVertices;
	m_lRenderStructs.push_back(renderStruct);
	node->SetVerticesName(renderStruct->verticesName);
	node->SetNormalsName(renderStruct->normalsName);
	node->SetTexCoordsName(renderStruct->texCoordsName);
	node->SetNumOfVertices(renderStruct->numOfVertices);

	return true;
}

//----------------------------------------------
/**
* Debug code to show bounding boxes
*/
void GLRenderer::ShowBoundingBoxes(GeometryNode* node)
{

	glColor3f(1.0, 1.0, 1.0);
	const BoundingBox& b = node->GetBoundingBox();
	mth::Vector3 nearUpL(b.minX, b.maxY, b.maxZ);
	mth::Vector3 nearUpR(b.maxX, b.maxY, b.maxZ);
	mth::Vector3 nearDownL(b.minX, b.minY, b.maxZ);
	mth::Vector3 nearDownR(b.maxX, b.minY, b.maxZ);
	mth::Vector3 farUpL(b.minX, b.maxY, b.minZ);
	mth::Vector3 farUpR(b.maxX, b.maxY, b.minZ);
	mth::Vector3 farDownL(b.minX, b.minY, b.minZ);
	mth::Vector3 farDownR(b.maxX, b.minY, b.minZ);

	glBegin(GL_LINES);
	glVertex3f(nearUpL.x, nearUpL.y, nearUpL.z);
	glVertex3f(nearUpR.x, nearUpR.y, nearUpR.z);
	
	glVertex3f(nearUpR.x, nearUpR.y, nearUpR.z);
	glVertex3f(nearDownR.x, nearDownR.y, nearDownR.z);

	glVertex3f(nearDownR.x, nearDownR.y, nearDownR.z);
	glVertex3f(nearDownL.x, nearDownL.y, nearDownL.z);

	glVertex3f(nearDownL.x, nearDownL.y, nearDownL.z);
	glVertex3f(nearUpL.x, nearUpL.y, nearUpL.z);

	glVertex3f(farUpL.x, farUpL.y, farUpL.z);
	glVertex3f(farUpR.x, farUpR.y, farUpR.z);
	
	glVertex3f(farUpR.x, farUpR.y, farUpR.z);
	glVertex3f(farDownR.x, farDownR.y, farDownR.z);

	glVertex3f(farDownR.x, farDownR.y, farDownR.z);
	glVertex3f(farDownL.x, farDownL.y, farDownL.z);

	glVertex3f(farDownL.x, farDownL.y, farDownL.z);
	glVertex3f(farUpL.x, farUpL.y, farUpL.z);

	glVertex3f(farDownL.x, farDownL.y, farDownL.z);
	glVertex3f(nearDownL.x, nearDownL.y, nearDownL.z);

	glVertex3f(farDownR.x, farDownR.y, farDownR.z);
	glVertex3f(nearDownR.x, nearDownR.y, nearDownR.z);

	glVertex3f(farUpL.x, farUpL.y, farUpL.z);
	glVertex3f(nearUpL.x, nearUpL.y, nearUpL.z);

	glVertex3f(farUpR.x, farUpR.y, farUpR.z);
	glVertex3f(nearUpR.x, nearUpR.y, nearUpR.z);


	glEnd();
		
		
}
//----------------------------------------------
/**
* Creates a display list for the skybox
*/
void GLRenderer::SetSkyBox(SkyBoxPtr skyBox)
{
	m_spSkyBox = skyBox;
	if (m_uiSkyBoxDL)
	{
		glDeleteLists(m_uiSkyBoxDL, 1);
	}

	m_uiSkyBoxDL = glGenLists(1);
	float size2 = m_spSkyBox->GetSize() / 2.0f;
	if (m_spSkyBox->IsTextured())
	{
		unsigned int textures[6];
		for (int i=0; i<6; i++)
		{
			textures[i] = m_spSkyBox->GetTexture(i)->GetId();
		}
		
		// if sky box has more than one textures
		if (m_spSkyBox->HasMultipleTextures())
		{
			glNewList(m_uiSkyBoxDL, GL_COMPILE);

			glEnable(GL_TEXTURE_2D);
			// far plane
			glBindTexture(GL_TEXTURE_2D, textures[SkyBox::PLANE_FAR]);
			glBegin(GL_QUADS);
			glTexCoord2f(0.0f, 1.0f);
			glVertex3f(-size2, size2, -size2);
			glTexCoord2f(0.0f, 0.0f);
			glVertex3f(-size2, -size2, -size2);
			glTexCoord2f(1.0f, 0.0f);
			glVertex3f(size2, -size2, -size2);
			glTexCoord2f(1.0f, 1.0f);
			glVertex3f(size2, size2, -size2);
			glEnd();

			// near plane
			glBindTexture(GL_TEXTURE_2D, textures[SkyBox::PLANE_NEAR]);
			glBegin(GL_QUADS);
			glTexCoord2f(0.0f, 1.0f);
			glVertex3f(size2, size2, size2);
			glTexCoord2f(0.0f, 0.0f);
			glVertex3f(size2, -size2, size2);
			glTexCoord2f(1.0f, 0.0f);
			glVertex3f(-size2, -size2, size2);
			glTexCoord2f(1.0f, 1.0f);
			glVertex3f(-size2, size2, size2);
			glEnd();

			// top plane
			glBindTexture(GL_TEXTURE_2D, textures[SkyBox::PLANE_TOP]);
			glBegin(GL_QUADS);
			glTexCoord2f(0.0f, 1.0f);
			glVertex3f(-size2, size2, size2);
			glTexCoord2f(0.0f, 0.0f);
			glVertex3f(-size2, size2, -size2);
			glTexCoord2f(1.0f, 0.0f);
			glVertex3f(size2, size2, -size2);
			glTexCoord2f(1.0f, 1.0f);
			glVertex3f(size2, size2, size2);
			glEnd();

			// bottom plane
			glBindTexture(GL_TEXTURE_2D, textures[SkyBox::PLANE_BOTTOM]);
			glBegin(GL_QUADS);
			glTexCoord2f(0.0f, 1.0f);
			glVertex3f(-size2, -size2, -size2);
			glTexCoord2f(0.0f, 0.0f);
			glVertex3f(-size2, -size2, size2);
			glTexCoord2f(1.0f, 0.0f);
			glVertex3f(size2, -size2, size2);
			glTexCoord2f(1.0f, 1.0f);
			glVertex3f(size2, -size2, -size2);
			glEnd();

			// right plane
			glBindTexture(GL_TEXTURE_2D, textures[SkyBox::PLANE_RIGHT]);
			glBegin(GL_QUADS);
			glTexCoord2f(0.0f, 1.0f);
			glVertex3f(size2, size2, -size2);
			glTexCoord2f(0.0f, 0.0f);
			glVertex3f(size2, -size2, -size2);
			glTexCoord2f(1.0f, 0.0f);
			glVertex3f(size2, -size2, size2);
			glTexCoord2f(1.0f, 1.0f);
			glVertex3f(size2, size2, size2);
			glEnd();

			// left plane
			glBindTexture(GL_TEXTURE_2D, textures[SkyBox::PLANE_LEFT]);
			glBegin(GL_QUADS);
			glTexCoord2f(0.0f, 1.0f);
			glVertex3f(-size2, size2, size2);
			glTexCoord2f(0.0f, 0.0f);
			glVertex3f(-size2, -size2, size2);
			glTexCoord2f(1.0f, 0.0f);
			glVertex3f(-size2, -size2, -size2);
			glTexCoord2f(1.0f, 1.0f);
			glVertex3f(-size2, size2, -size2);
			glEnd();

			glDisable(GL_TEXTURE_2D);

			glEndList();
		}
		// skybox has one texture
		else
		{
			glNewList(m_uiSkyBoxDL, GL_COMPILE);

			glEnable(GL_TEXTURE_2D);
			// far plane
			glBindTexture(GL_TEXTURE_2D, textures[0]);
			glBegin(GL_QUADS);
			glTexCoord2f(0.0f, 1.0f);
			glVertex3f(-size2, size2, -size2);
			glTexCoord2f(0.0f, 0.0f);
			glVertex3f(-size2, -size2, -size2);
			glTexCoord2f(1.0f, 0.0f);
			glVertex3f(size2, -size2, -size2);
			glTexCoord2f(1.0f, 1.0f);
			glVertex3f(size2, size2, -size2);
			glEnd();

			// near plane
			glBegin(GL_QUADS);
			glTexCoord2f(0.0f, 1.0f);
			glVertex3f(size2, size2, size2);
			glTexCoord2f(0.0f, 0.0f);
			glVertex3f(size2, -size2, size2);
			glTexCoord2f(1.0f, 0.0f);
			glVertex3f(-size2, -size2, size2);
			glTexCoord2f(1.0f, 1.0f);
			glVertex3f(-size2, size2, size2);
			glEnd();

			// top plane
			glBegin(GL_QUADS);
			glTexCoord2f(0.0f, 1.0f);
			glVertex3f(-size2, size2, size2);
			glTexCoord2f(0.0f, 0.0f);
			glVertex3f(-size2, size2, -size2);
			glTexCoord2f(1.0f, 0.0f);
			glVertex3f(size2, size2, -size2);
			glTexCoord2f(1.0f, 1.0f);
			glVertex3f(size2, size2, size2);
			glEnd();

			// bottom plane
			glBegin(GL_QUADS);
			glTexCoord2f(0.0f, 1.0f);
			glVertex3f(-size2, -size2, -size2);
			glTexCoord2f(0.0f, 0.0f);
			glVertex3f(-size2, -size2, size2);
			glTexCoord2f(1.0f, 0.0f);
			glVertex3f(size2, -size2, size2);
			glTexCoord2f(1.0f, 1.0f);
			glVertex3f(size2, -size2, -size2);
			glEnd();

			// right plane
			glBegin(GL_QUADS);
			glTexCoord2f(0.0f, 1.0f);
			glVertex3f(size2, size2, -size2);
			glTexCoord2f(0.0f, 0.0f);
			glVertex3f(size2, -size2, -size2);
			glTexCoord2f(1.0f, 0.0f);
			glVertex3f(size2, -size2, size2);
			glTexCoord2f(1.0f, 1.0f);
			glVertex3f(size2, size2, size2);
			glEnd();

			// left plane
			glBegin(GL_QUADS);
			glTexCoord2f(0.0f, 1.0f);
			glVertex3f(-size2, size2, size2);
			glTexCoord2f(0.0f, 0.0f);
			glVertex3f(-size2, -size2, size2);
			glTexCoord2f(1.0f, 0.0f);
			glVertex3f(-size2, -size2, -size2);
			glTexCoord2f(1.0f, 1.0f);
			glVertex3f(-size2, size2, -size2);
			glEnd();

			glDisable(GL_TEXTURE_2D);

			glEndList();
		}
				
	}
	// skybox has no texture
	else
	{
		glNewList(m_uiSkyBoxDL, GL_COMPILE);

		glColor3f(m_vBackgroundColor.x, m_vBackgroundColor.y, m_vBackgroundColor.z);
		// far plane
		glBegin(GL_QUADS);
		glVertex3f(-size2, size2, -size2);
		glVertex3f(-size2, -size2, -size2);
		glVertex3f(size2, -size2, -size2);
		glVertex3f(size2, size2, -size2);
		glEnd();

		// near plane
		glBegin(GL_QUADS);
		glVertex3f(size2, size2, size2);
		glVertex3f(size2, -size2, size2);
		glVertex3f(-size2, -size2, size2);
		glVertex3f(-size2, size2, size2);
		glEnd();

		// top plane
		glBegin(GL_QUADS);
		glVertex3f(-size2, size2, size2);
		glVertex3f(-size2, size2, -size2);
		glVertex3f(size2, size2, -size2);
		glVertex3f(size2, size2, size2);
		glEnd();

		// bottom plane
		glBegin(GL_QUADS);
		glVertex3f(-size2, -size2, -size2);
		glVertex3f(-size2, -size2, size2);
		glVertex3f(size2, -size2, size2);
		glVertex3f(size2, -size2, -size2);
		glEnd();

		// right plane
		glBegin(GL_QUADS);
		glVertex3f(size2, size2, -size2);
		glVertex3f(size2, -size2, -size2);
		glVertex3f(size2, -size2, size2);
		glVertex3f(size2, size2, size2);
		glEnd();

		// left plane
		glBegin(GL_QUADS);
		glVertex3f(-size2, size2, size2);
		glVertex3f(-size2, -size2, size2);
		glVertex3f(-size2, -size2, -size2);
		glVertex3f(-size2, size2, -size2);
		glEnd();


		glEndList();
	}
}
//----------------------------------------------
/**
* Opengl.Org code: checks if VBO's are supported
*/
bool GLRenderer::IsVBOExtensionSupported()
{
	const unsigned char *pszExtensions = NULL;
	const unsigned char *pszStart;
	char* szTargetExtension = "GL_ARB_vertex_buffer_object";
	unsigned char *pszWhere, *pszTerminator;

	// Extension names should not have spaces
	pszWhere = (unsigned char *) strchr( szTargetExtension, ' ' );
	if( pszWhere || *szTargetExtension == '\0' )
		return false;

	// Get Extensions String
	pszExtensions = glGetString( GL_EXTENSIONS );

	// Search The Extensions String For An Exact Copy
	pszStart = pszExtensions;
	for(;;)
	{
		pszWhere = (unsigned char *) strstr( (const char *) pszStart, szTargetExtension );
		if( !pszWhere )
			break;
		pszTerminator = pszWhere + strlen( szTargetExtension );
		if( pszWhere == pszStart || *( pszWhere - 1 ) == ' ' )
			if( *pszTerminator == ' ' || *pszTerminator == '\0' )
				return true;
		pszStart = pszTerminator;
	}
	return false;
}

